# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2013-Today OpenERP SA (<http://www.openerp.com>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp.osv import osv
from openerp.osv import fields


class customer_address(osv.osv):
    _name = 'customer.address'
    _order = 'default desc, id desc'
    _rec_name = 'name'
    def set_default(self, cr, uid, id, context=None):
        address = self.browse(cr, uid, id, context=context)

        for line in address.partner_id.multi_address_ids:
            default = line.id == address.id
            if line.default != default:
                line.write({'default': default})

    def onchange_province(self, *args, **kwargs):
        delegate_obj = self.pool.get('china.city.county')

        return delegate_obj.onchange_province(*args, **kwargs)

    def onchange_county(self, *args, **kwargs):
        delegate_obj = self.pool.get('china.city.county')

        return delegate_obj.onchange_county(*args, **kwargs)

    def onchange_city(self, *args, **kwargs):
        delegate_obj = self.pool.get('china.city.county')

        return delegate_obj.onchange_city(*args, **kwargs)

    def get_addresss_by_partner(self, cr, uid, partner_id, context=None):
        address_ids = self.search(cr, uid, [('partner_id', '=', partner_id),
                                            ('state', '=', 'use')], context=context)

        res = []
        for address in self.browse(cr, uid, address_ids, context=context):
            res.append(self._get_address_detail(cr, uid, address, context=context))

        return res

    def _get_address_detail(self, cr, uid, address, context=None):
        if isinstance(address, (long, int)):
            address = self.browse(cr, uid, address, context=context)

        return {
            'id': address.id,
            'name': address.name,
            'zip': address.zip,
            'phone': address.phone,
            'street': address.street,
            'province': {'id': address.province_id.id, 'name': address.province_id.name},
            'city': {'id': address.city_id.id, 'name': address.city_id.city_name},
            'county': {'id': address.county_id.id, 'name': address.county_id.county_name},
            'choose': address.default,
            'delete': False,
        }

    def get_default_address(self, cr, uid, partner_id, context=None):
        address_ids = self.search(cr, uid, [('partner_id', '=', partner_id),
                                            ('state', '=', 'use'),
                                            ('default', '=', True)], context=context)

        if not address_ids:
            address_ids = self.search(cr, uid, [('partner_id', '=', partner_id),
                                            ('state', '=', 'use')], context=context)

        if not address_ids:
            return ''

        return self._get_address_detail(cr, uid, address_ids[0], context=context)

    def get_address(self, cr, uid, address, context=None):
        if isinstance(address, (long, int)):
            address = self.browse(cr, uid, address, context=context)

        return {
            'name': address.name,
            'phone': address.phone,
            'zip': address.zip,
            'street': address.street,
            'address': ['state-%s' % address.province_id.id,
                        'city-%s' % address.city_id.id,
                        'county-%s' % address.county_id.id],
        }
    def write(self, cr, uid, ids, vals, context=None):
        primary_contact_ids = self.pool.get('res.partner').search(cr, uid, [('purchase_default_contact_id',
                                                                          'in', ids)], context=context)
        if vals.get('mobile_number') or vals.get('phone_number') and primary_contact_ids:
            phone_vals = {}
            if vals.get('mobile_number'):
                phone_vals.update({'mobile': vals.get('mobile_number')})
            if vals.get('phone_number'):
                phone_vals.update({'phone': vals.get('phone_number')})
            self.pool.get('res.partner').write(cr, uid, primary_contact_ids, phone_vals, context=context)
        return super(customer_address, self).write(cr, uid, ids, vals, context=context)

    _columns = {
        'partner_id': fields.many2one('res.partner', u'客户'),
        'province_id': fields.many2one('res.country.state', u'省'),
        'city_id': fields.many2one('all.city', u'市'),
        'county_id': fields.many2one('all.county', u'县'),
        'street': fields.char(u'详细地址'),
        'zip': fields.char(u'邮政编码'),
        'default': fields.boolean(u'默认地址'),
        'name': fields.char(u'联系人', size=64, required=True),
        'phone': fields.char(u'手机号码', size=64),
        'note': fields.text(u'备注'),
        'state': fields.selection([('use', u'使用中'), ('cancel', u'取消')], string=u'状态'),

        # TODO @正翔 以前的字段，为了保持兼容性，暂时留下这些字段
        'state': fields.selection([('use', u'使用中'), ('cancel', u'取消')], string=u'状态'),
        'sexual': fields.char(u'性别', size=64),
        'contacts': fields.char(u'联系人', size=64),
        'phone_number': fields.char(u'电话号', size=64),
        'mobile_number': fields.char(u'手机号', size=64),
        'fax': fields.char(u'传真'),
        'department': fields.char(u'部门'),
        'birthday': fields.date(u'生日'),
        'duties': fields.char(u'职务', size=64),
        'title': fields.many2one('res.partner.title', string='称谓'),
        'email': fields.char(u'邮箱', size=64),
        'QQ': fields.char(u'QQ', size=64),
        # 团购扩展字段
        'home_phone': fields.char(u'家庭电话'),
        # 联系人上的用户，用来存储联系人关联的partner上的user
        'user_id': fields.many2one('res.users', u'用户'),
        'is_subscription': fields.boolean(u'是否邮寄'),
    }

    _defaults = {
        'state': 'use',
    }


class res_partner(osv.osv):
    _inherit = 'res.partner'

    _columns = {
        'multi_address_ids': fields.one2many('customer.address', 'partner_id', u'收货地址'),
        'purchase_default_contact_id': fields.many2one('customer.address', u'默认联系人'),
    }

    def create(self, cr, uid, vals, context=None):

        if vals.get('purchase_default_contact_id'):
            customer_row = self.pool.get('customer.address').browse(cr, uid, vals.get('purchase_default_contact_id'),
                                                                    context=context)
            vals.update({'phone': customer_row.phone_number,
                         'mobile': customer_row.mobile_number
                         })
        return super(res_partner, self).create(cr, uid, vals, context=context)

    def write(self, cr, uid, ids, vals, context=None):
        if vals.get('purchase_default_contact_id'):
            customer_row = self.pool.get('customer.address').browse(cr, uid, vals.get('purchase_default_contact_id'),
                                                                    context=context)
            vals.update({'phone': customer_row.phone_number,
                         'mobile': customer_row.mobile_number
                         })
        return super(res_partner, self).write(cr, uid, ids, vals, context=context)

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
